import os
import pandas as pd
from datetime import datetime, timedelta

from analysis.option_value_risk_analysis import fetch_option_risk_value, calculate_option_value


def option_position_analysis():
    position_dir = "D:\work\other_side_happiness\dfcf/持仓"
    # 20250630_poistion_qq.txt
    pattern = datetime.now().strftime("%Y%m%d")
    file_name = os.path.join(position_dir, f"{pattern}_poistion_qq.txt")

    # 如果找不到当天的文件，尝试查找昨天的文件
    if not os.path.exists(file_name):
        yesterday = datetime.now() - timedelta(days=1)
        yesterday_pattern = yesterday.strftime("%Y%m%d")
        file_name = os.path.join(position_dir, f"{yesterday_pattern}_poistion_qq.txt")
        if not os.path.exists(file_name):
            raise ValueError(f"not found option_position_file for today ({pattern}) or yesterday ({yesterday_pattern})")
        pattern = yesterday_pattern
    print(f"using option_position_file:{file_name}")
    position_df = pd.read_csv(file_name, sep=r'\s{2,}', engine='python', encoding='gbk')

    position_df["合约编码"] = pd.to_numeric(position_df["合约编码"], errors="coerce")

    print(position_df)
    value_df = fetch_option_risk_value()
    value_df = calculate_option_value(value_df)
    print(value_df)
    merged_df = pd.merge(
        position_df,
        value_df,
        left_on='合约编码',
        right_on='期权代码',  # 使用右侧索引作为关联键
        how='left'
    )
    print(merged_df)
    merged_df.to_csv("../result/option_position_analysis.csv")
    # 增加一列“剩余交易日”，为当前时间到到期时间，中间排除掉周六周日
    # 这里用 pandas 的 bdate_range 只统计工作日（即自动排除了周六周日）
    if "到期日" in merged_df.columns:
        def calc_trading_days(expiry_str):
            try:
                expiry = pd.to_datetime(expiry_str)
                today = pd.to_datetime(datetime.now().date())
                # 只统计 today+1 到 expiry 之间的工作日（不含今天）
                if expiry <= today:
                    return 0
                # pd.bdate_range 只返回工作日（周一到周五），自动排除周六周日
                days = pd.bdate_range(today, expiry)
                # days = pd.bdate_range(today + pd.Timedelta(days=1), expiry)
                return len(days)
            except Exception:
                return ""

        merged_df["剩余交易日"] = merged_df["到期日"].apply(calc_trading_days)
    else:
        merged_df["剩余交易日"] = ""

    # 增加浮盈率列，保留两位小数
    merged_df["浮盈率"] = (merged_df["浮动盈亏"] / merged_df["合约买入成本"] * 100).round(2)
    merged_df["浮盈率"] = merged_df["浮盈率"].apply(lambda x: f"{x:.2f}" if pd.notnull(x) else "")

    # # 调整浮盈率列顺序到浮动盈亏后面
    # cols = list(merged_df.columns)
    # cols.remove("浮盈率")
    # idx = cols.index("浮动盈亏") + 1
    # merged_df = merged_df[cols]

    merged_df = merged_df[["合约简称",
                           "持仓数量",
                           "合约买入成本",
                           "市值",
                           "浮动盈亏",
                           "浮盈率",
                           "保证金_x",
                           "最新价",
                           "理论价格",
                           "Delta",
                           "Vega",
                           "Theta",
                           "虚值度",
                           "收益率",
                           "年化收益率",
                           "剩余天数",
                           "剩余交易日",
                           ]]
    # 保留指定列4位小数
    float_cols = ["最新价", "理论价格", "Delta", "Vega", "Theta"]
    for col in float_cols:
        if col in merged_df.columns:
            merged_df[col] = merged_df[col].apply(lambda x: f"{x:.4f}" if pd.notnull(x) else "")
    merged_df = merged_df.sort_values("剩余天数", ascending=True)
    merged_df.to_csv(f"../result/option_position_analysis_simple_{pattern}.csv", index=False)


if __name__ == '__main__':
    option_df = option_position_analysis()
